package com.dxb.ssoserver.config;

import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Map;

/**
 * 自动授权,不必手动点击一次
 * @author DLS
 */
@Controller
@SessionAttributes("authorizationRequest")
@Primary
public class SsoApprovalEndpoint {
    private static final String HTML_TEMPLATE;

    static {
        try {
            Resource resource = new ClassPathResource("static/default.html");
            FileReader fr = new FileReader(resource.getFile());
            BufferedReader br = new BufferedReader(fr);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            HTML_TEMPLATE = sb.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @RequestMapping("/oauth/confirm_access")
    public ModelAndView getAccessConfirmation(Map<String, Object> model, HttpServletRequest request) throws Exception {
        if (request.getAttribute("_csrf") != null) {
            model.put("_csrf", request.getAttribute("_csrf"));
        }
        View approvalView = new View() {
            @Override
            public String getContentType() {
                return "text/html";
            }

            @Override
            public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
                response.setContentType(getContentType());
                response.getWriter().append(HTML_TEMPLATE);
            }
        };
        return new ModelAndView(approvalView, model);
    }


}
